<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
namespace core;
defined('BY_JYA') or exit('error');
class files{
	private $setting;
	public function __construct(){
		$this->setting=IS_UNI_ATTACHMENT==1?uni_setting('upload'):core_setting('upload');
	}
	//压缩
	public function zip($dir, $to,$ignore=array(),$types=array(),$filename='') {
		if(!$dir){
			exi('压缩失败，缺少源文件！','error');
		}
		if($to=='data' || $to=='source'){
			$temp=ROOT_AT.random(15).'.z';
		}else{
			$temp=$to;
		}
		//if(function_exists('exec')){
		//	exec('cd '.$dir.' && zip -q -r '.$temp.' ./*');
		//}else{
			$tree=$this->file_tree($dir,$ignore,$types);
			if(!class_exists('\ZipArchive')){
				return error('检测不到类：ZipArchive');
			}
			$zip = new \ZipArchive();
			$zip->open($temp, \ZipArchive::CREATE);
			foreach($tree as $v) {
				$fname = $dir . $v;
				$zip->addFile($fname,$v);
			}
			$zip->close();
		//}
		if(!is_file($temp)){
			exi('文件压缩失败！','error');
		}
		if($to=='data'){
			$return=file_get_contents($temp);
		}elseif($to=='source'){
			$return= $this->source_save($temp,'data','zip','',$filename);
		}else{
			return true;
		}
		@unlink($temp);
		return $return;
	}
	//解压
	public function unzip($file, $to) {
		if(!class_exists('\ZipArchive')){
			return error('检测不到类：ZipArchive');
		}
		$zip = new \ZipArchive();
		$zip->open($file);
		$zip->extractTo($to);
		$zip->close();
		return true;
	}
	//创建目录树
	public function make_tree($path,&$trees,$ignores=array(),$exts=array(),$repath='',$num=0){
		$count=count($trees);
		if(!$repath){
			$repath=$path;
		}
		$tree=scandir($path);
		foreach($tree as $row){
			if($row!='.' && $row!='..'){
				//判断是否忽略
				$file_dir=str_replace($repath,'',$path.'/'.$row);
				if($ignores && in_array($file_dir,$ignores)){
					continue;
				}
				$temp=array('name'=>$row,'num'=>$num);
				if($count){
					$temp['father']=$count-1;
				}
				if(is_dir($path.'/'.$row)){
					$temp['type']=1;
					$temp['id']=$file_dir;
					$trees[]=$temp;
					$this->make_tree($path.'/'.$row,$trees,$ignores,$exts,$repath,$num+1);
				}else{
					$ext=$this->get_ext($row);
					if(!$exts || in_array($ext,$exts)){
						$temp['type']=2;
						$temp['id']=$file_dir;
						$trees[]=$temp;
					}
					
				}
			}
		}
		$temp=array('name'=>'添加','num'=>$num,'type'=>3,'dir'=>str_replace($repath,'',$path));
		if($count){
			$temp['father']=$count-1;
		}
		$trees[]=$temp;
	}
	public function get_ext($file){
		if(!$file){
			return false;
		}
		$ext=strrchr($file,'.');
		if(!$ext){
			return false;
		}
		return substr($ext,1);
	}
	//获取指定目录文件列表
	public function file_tree($path,$ignore=array(),$types=array(),$rpath='') {
		if(!is_array($ignore)){
			$ignore=array($ignore);
		}
		if(!is_array($types)){
			$types=array($types);
		}
		$files = array();
		if(!$rpath){
			$rpath=$path;
		}
		$ds = glob($path . '/*');
		if (is_array($ds)) {
			foreach ($ds as $entry) {
				$entry=str_replace('\\', '/', $entry);
				$entry=str_replace($rpath, '', $entry);
				if(in_array($entry,$ignore)){
					continue;
				}
				if (is_file($rpath.$entry)) {
					
					if(empty($types)){
						$files[] = $entry;
					}else{
						$type=strrchr($entry,'.');
						if(in_array($type,$types)){
							$files[] = $entry;
						}
					}
				}
				if (is_dir($rpath.$entry)) {
					$rs = $this->file_tree($rpath.$entry,$ignore,$types,$rpath);
					foreach ($rs as $f) {
						$files[] = $f;
					}
				}
			}
		}
		return $files;
	}
	//递归创建目录
	public function mkdirs($path) {
		
		if (!is_dir($path)) {
			$this->mkdirs(dirname($path));
			mkdir($path);
		}
		return is_dir($path);
	}
	//复制文件夹
	public function file_copy($src, $des) {
		$dir = opendir($src);
		@mkdir($des);
		while (false !== ($file = readdir($dir))) {
			if (($file != '.') && ($file != '..')) {
				if (is_dir($src . '/' . $file)) {
					$this->file_copy($src . '/' . $file, $des . '/' . $file);
				} else{
					copy($src . '/' . $file, $des . '/' . $file);
				}
			}
		}
		closedir($dir);
	}
	//递归删除指定目录下的所有子文件夹和文件，第二项为真保留指定目录，否则连同指定目录一起删除
	public function rmdirs($path, $hold = false) {
		if (!is_dir($path)) {
			return false;
		}
		$files = glob($path . '/*');
		if ($files) {
			foreach ($files as $file) {
				is_dir($file) ? $this->rmdirs($file) : @unlink($file);
			}
		}
		return $hold ? true : @rmdir($path);
	}
	//生成附件文件路径
	public function get_source_name($type,$ext='data'){
		$ext=$ext?:'data';
		$this->mkdirs(ROOT_AT.'oss/'.$_SESSION['uniacid'].'/'.$type.'s/'.date('Y/m'));
		do {
			$filename = 'oss/'.$_SESSION['uniacid'].'/'.$type.'s/'.date('Y/m').'/'.random(10) . '.' . $ext;
		} while (file_exists(ROOT_AT .$filename));
		return $filename;
	}
	//检查附件是否存在
	public function source_check($file,$isonlyfile=false,$isonlyid=false){
		if(!$isonlyfile){
			$id=pdo_getcolumn('core_attachment',array('attachment'=>$file,'uniacid'=>$_SESSION['uniacid']),'id');
		}
		if($id || $isonlyfile){
			if($isonlyid){
				return true;
			}
			if (ATTACHMENT_TYPE == '0'){
				$file=ROOT_AT.$file;
				if(is_file($file)){
					return true;
				}
			}else{
				$file=ATTACHMENT_URL.$file;
				if(@fopen($file,'r')){
					return true;
				}
			}
			return false;
		}else{
			return false;
		}
	}
	//读取附件内容$isroot表示只读取系统的
	public function source_read($file,$isroot=false){
		global $_AR;
		//优先读取本地
		if($isroot){
			$file=ROOT_AT.$file;
			if(is_file($file)){
				return @file_get_contents($file);
			}
		}
		if (ATTACHMENT_TYPE == '0') {
				$file=ROOT_AT.$file;
				if(!is_file($file)){
					return false;
				}
		}elseif(ATTACHMENT_TYPE == '5'){
				$data=$this->source_diy_request('read',array('file'=>$file),$isroot);
				return $data;
		}else{
				$file=ATTACHMENT_URL.$file;
		}
		return @file_get_contents($file);
	}
	public function url_source_save($url,$type='image',$title=''){
		$data=file_get_contents($url);
		if(!$data){
			return error('url资源无效');
		}
		$ext=substr(strrchr($url,'.'),1);
		return $this->source_save($data,$type,$ext,$title);
	}
	//将附件保存到本地，并返回本地路径
	public function local($file){
		$local_file=ROOT_AT.$file;
		if(ATTACHMENT_TYPE){
			$file_data=$this->source_read($file);
			$this->mkdirs(dirname($local_file));
			file_put_contents($local_file,$file_data);
		}
		return $local_file;
	}
	public function wechat_image_url($image){
		$attachment=pdo_get('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'type'=>'image','attachment'=>$image),array('id','wx_url'));
		if(!$attachment){
			return '';
		}else{
			if(!$attachment['wx_url']){
				$api_url='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={access_token}';
				$local=$this->local($image);
				$params=array(
					'media'=>'@'.$local,
				);
				$res=cfc('account')->request($api_url,$params);
				if($res['url']){
					$attachment['wx_url']=$res['url'];
					pdo_update('core_attachment',array('wx_url'=>$res['url']),array('id'=>$attachment['id']));
				}
			}
			return $attachment['wx_url'];
		}
	}
	//保存附件
	public function source_save($from,$type='data',$ext='data',$title='未设置标题',$filename='',$group_id=0,$wx_url='',$islocal=false,$group_id2=0){
		//附件保存功能。$from支持文件路径和文件内容两种形式。$filename如果为空，系统将自动创建附件路径，保存成后，函数返回附件相对路径。
		global $_AR;
		if(!$type){
			$type='data';
		}
		if($type=='nochoose'){
			$nochoose=1;
			$type='image';
		}
		if(!$ext){
			$ext='data';
		}
		$check=@is_file($from);
		if(!$check){
			$check=@is_file(ROOT_AT.$from);
			if($check){
				$from=ROOT_AT.$from;
			}
		}
		if(!$check){
			$temp=ROOT_AT.random(30).'.temp';
			//写入文件
			file_put_contents($temp,$from);
			$from=$temp;
		}
		$md5=md5_file($from);
		//检查是否有相同文件
		if($type=='image' || $type=='video' || $type=='audio'){
			$check=pdo_getcolumn('core_attachment',array('md5'=>$md5,'type'=>$type,'mid'=>$_SESSION['this']=='custom'?$_SESSION['uid']:0,'uniacid'=>$_SESSION['uniacid']),'attachment');
			if($wx_url && !$check){
				$check=pdo_getcolumn('core_attachment',array('wx_url'=>$wx_url,'type'=>$type,'mid'=>$_SESSION['this']=='custom'?$_SESSION['uid']:0,'uniacid'=>$_SESSION['uniacid']),'attachment');
			}
			if($check){
				$isadd=$this->source_check($check);
				if ($isadd) {
					pdo_update('core_attachment',array('uptime'=>TIMESTAMP),array('attachment'=>$check,'type'=>$type,'uniacid'=>$_SESSION['uniacid']));
					return $check;
				}
			}
		}
		$size=filesize($from);
		//检查站点附件容量是否达到上限
		if($_SESSION['uniacid']>1 && !$_SESSION['isresource_limit']){
			$resource_limit=model('core/web')->get_resource_limit($_SESSION['uniacid']);
			$total_size=pdo_fetch('select sum(`size`) from `'.TABLE_PRE.'core_attachment` where `uniacid`='.$_SESSION['uniacid']);
			$total_size=$total_size['sum(`size`)'];
			if($resource_limit && $resource_limit<$total_size){
				exi('您的站点附件已超出套餐容量限制，无法再上传附件资源！请先整理站点附件或者升级套餐！','error');
			}else{
				$_SESSION['isresource_limit']=1;
			}
		}
		//如果启用图片压缩。则检查图片是否太大，如果太大，则对图片进行压缩
		if($filename){
			$key=intval($filename);
			if($key){
				$filename=pdo_getcolumn('core_attachment',array('id'=>$key),'attachment');
			}else{
				$isaddfile=pdo_getcolumn('core_attachment',array('attachment'=>$filename),'id');
				$is_new=$isaddfile?false:true;
			}
		}
		if(!$filename){
			$is_new=true;
			$filename=$this->get_source_name($type,$ext);
		}
		if($this->setting['thumb'] && $type=='image'){
			$thumb=true;
			$from=$this->file_image_thumb($from);
		}
		if (ATTACHMENT_TYPE == '0' || $islocal) {
			copy($from,ROOT_AT.$filename);
		}elseif (ATTACHMENT_TYPE == '1'){
			$this->source_save_ftp($from,$filename);
		}elseif (ATTACHMENT_TYPE == '2') {
		    $this->source_save_oss($from,$filename);
		}elseif (ATTACHMENT_TYPE == '3') {
		    if(!$is_new){
				//尝试删除已存在的文件
				 require_once(ROOT_D . '/core/library/qiniu/autoload.php');
                $auth = qndel($this->setting['qiniu_accesskey'], $this->setting['qiniu_secretkey']);
                $config = new \Qiniu\Config();
                $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
                $err = $bucketManager->delete($this->setting['qiniu_bucket'], $filename);
			}
			$this->source_save_qiniu($from,$filename);
		} elseif (ATTACHMENT_TYPE == '4') {	
			$this->source_save_cos($from,$filename);
		}elseif (ATTACHMENT_TYPE == '5') {	
			//自定义资源站
			$this->source_save_diy($from,$filename);
		}
		if($temp){
			@unlink($temp);
		}
		if($thumb){
			@unlink($from);
		}
		if($is_new){
			$insert=array(
				'uniacid' => $_SESSION['uniacid'],
				'mid' => $_SESSION['this']=='custom'?$_SESSION['uid']:0,
				'group_id'=>$group_id,
				'group_id2'=>$group_id2,
				'title' => $title,
				'attachment' => $filename,
				'type' => $type,
				'uptime'=>TIMESTAMP,
				'createtime' => TIMESTAMP,
				'md5'=>$md5,
				'size'=>$size,
				'wx_url'=>$wx_url,
				'nochoose'=>$nochoose
			);
			pdo_insert('core_attachment',$insert);
		}
		return $filename;
	}
	//保存FTP
	public function source_save_ftp($from,$filename){
			require_once(ROOT_D . '/core/library/ftp/ftp.php');
			if(!$this->setting['ftp_ip'] || !$this->setting['ftp_user'] || !$this->setting['ftp_psw']|| !$this->setting['ftp_dk']){
				exi('必要参数没有设置，上传失败！','error');
			}
			$ftp_config = array(
				'hostname' => $this->setting['ftp_ip'],
				'username' => $this->setting['ftp_user'],
				'password' => $this->setting['ftp_psw'],
				'port' => $this->setting['ftp_dk'],
				'ftp_ssl' => $this->setting['ftp_ssl'],
				'ftp_pasv2' => $this->setting['ftp_pasv'],
				'ftp_dir' => $this->setting['ftp_dir'],
			);
			$ftp = new Ftp($ftp_config);
			if (true === $ftp->connect()) {
				$source = $ftp->upload($from, $filename);
				if (empty($source)) {
					exi('上传失败！检查配置和权限！');
				}
			}
	}
	//保存七牛云附件
	public function source_save_qiniu($from,$filename){
		if(!$this->setting['qiniu_accesskey'] || !$this->setting['qiniu_secretkey'] || !$this->setting['qiniu_bucket']){
			exi('七牛云参数设置异常，无法上传！','error');
		}
		require_once(ROOT_D . '/core/library/qiniu/autoload.php');
		$accessKey = $this->setting['qiniu_accesskey'];
		$secretKey = $this->setting['qiniu_secretkey'];
		$bucket = $this->setting['qiniu_bucket'];
		$auth = auth($accessKey, $secretKey);
		// 生成上传 Token
		$token = $auth->uploadToken($bucket);
		// 要上传文件的本地路径
		$filePath = $from;
		// 上传到七牛后保存的文件名
		$key = $filename;
		// 初始化 UploadManager 对象并进行文件的上传。
		$uploadMgr = uploadMgr();
		// 调用 UploadManager 的 putFile 方法进行文件的上传。
		list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
		if($err !== null && !$_SESSION['fromh5wxapp'] && $_SESSION['container']!='wxapp'){
		    exi('七牛上传失败：请检测配置！','error');
		}
		return true;
	}
	//保存阿里云oss附件
	public function source_save_oss($from,$filename){
		if(!$this->setting['ali_accessid'] || !$this->setting['ali_accesskey'] || !$this->setting['ali_endpoint'] || !$this->setting['ali_bucket']){
				exi('阿里云oss参数设置异常，无法上传！','error');
		}
	    require_once(ROOT_D.'/core/library/alioss/autoload.php');	    
		$ossClient = make_oss_Client($this->setting['ali_accessid'], $this->setting['ali_accesskey'], $this->setting['ali_endpoint']);
		$bucketlistinfo =$ossClient->doesBucketExist($this->setting['ali_bucket']);
		if($bucketlistinfo!==true){
			exi('空间不存在','error');   
		}
		$ossClient->uploadFile($this->setting['ali_bucket'], $filename,$from);
	}
	//保存腾讯云附件
	public function source_save_cos($from,$filename){
			if(!$this->setting['tx_appid'] || !$this->setting['tx_secretid'] || !$this->setting['tx_secretkey']){
				exi('腾讯云oss参数设置异常，无法上传！','error');
			}
			require_once(ROOT_D.'/core/library/cosv5/index.php');
			$config = array(
                'app_id' => $this->setting['tx_appid'],
                'secret_id' => $this->setting['tx_secretid'],
                'secret_key' => $this->setting['tx_secretkey'],
                'region' => $this->setting['tx_region'],
                'timeout' => 60
            );
            try {
				$bucket = $this->setting['tx_bucket'] . '-' . $config['app_id'];
				$cosClient = new \Qcloud\Cos\Client(
					array(
						'region' => $config['region'],
						'credentials'=> array(
							'secretId'  => $config['secret_id'],
							'secretKey' => $config['secret_key']
						)
					)
				);
				$cosClient->Upload($bucket, $filename, fopen($from, 'rb'));
			} catch (\Exception $e) {
				$errormsg=$e->getMessage();
				exi($errormsg,'error');
			}	
	}
	//保存附件至自定义资源站
	public function source_save_diy($from,$filename){
		$temp=random(30).'zip';
		copy($from,ROOT_AT.$temp);
		$source=SITEROOT.RESOURCE.'/'.$temp;
		$post=array(
			'from'=>$source,
			'to'=>$filename,
		);
		$this->source_diy_request('add',$post);
		@unlink(ROOT_AT.$temp);
		return true;
	}
	private function source_diy_request($do,$par,$isroot=false){
		if($isroot && IS_UNI_ATTACHMENT==1){
			$this->setting=core_setting('upload');
			if($this->setting['jya_request']){
				$post_url=$this->setting['jya_request'].'/resource.php';
			}elseif($this->setting['jya_url']){
				$post_url=$this->setting['jya_url'].'/resource.php';
			}else{
				exi('系统附件设置未设置资源请求地址！','error');
			}
		}else{
			if($this->setting['jya_request']){
				$post_url=$this->setting['jya_request'].'/resource.php';
			}elseif($this->setting['jya_url']){
				$post_url=$this->setting['jya_url'].'/resource.php';
			}else{
				exi('系统附件设置未设置资源请求地址！','error');
			}
		}
		$post=array(
			'do'=>$do,
			'data'=>$par,
			'timestamp'=>TIMESTAMP,
		);
		$post=cfc('tools')->base64_encode(ijson_encode($post));
		if($isroot || IS_UNI_ATTACHMENT==0){
			$source_key=core_setting('source_key');
		}else{
			$source_key=unit_setting('source_key');
		}
		$source_key=$source_key['source_key'];
		if(!$source_key){
			exi('附件上传失败1！','error');
		}
		$sign=md5($post.$source_key);
		$post=$sign.$post;
		$params=array(
			'data'=>$post,
		);
		$res=cfc('http')->ihttp_request($post_url,$params);
		if(!$res['content']){
			exi('访问附件资源站失败！没有收到数据：'.$res['code'],'error');
		}
		$res=$res['content'];
		$res=@unserialize(base64_decode($res));
		if($res['type']=='success'){
			return $res['message'];
		}else{
			exi('访问附件资源站失败！错误详情：'.$res['message'],'error');
		}
	}
	//删除附件
	public function source_del($id){
	    	global $_AR;
		if(intval($id)){
			$isid=true;
			$filename=pdo_getcolumn('core_attachment',array('uniacid'=>$_SESSION['uniacid'],'id'=>$id),'attachment');
		}else{
			$filename=$id;
		}
		if(!$filename){
			return false;
		}
		if(ATTACHMENT_TYPE == '0'){
    		if(is_file(ROOT_AT.$filename)){
    			@unlink(ROOT_AT.$filename);
    		}
		}else{
		       if(ATTACHMENT_TYPE == '1'){
				   require_once(ROOT_D.'/core/library/alioss/autoload.php');
					$ftp_config = array(
						'hostname' => $_W['setting']['remote']['ftp']['hostname'] ?: $_W['setting']['remote']['ftp']['host'],
						'username' => $_W['setting']['remote']['ftp']['username'],
						'password' => $_W['setting']['remote']['ftp']['password'],
						'port' => $_W['setting']['remote']['ftp']['port'],
						'ssl' => $_W['setting']['remote']['ftp']['ssl'],
						'passive' => $_W['setting']['remote']['ftp']['passive'] ?: $_W['setting']['remote']['ftp']['pasv'],
						'timeout' => $_W['setting']['remote']['ftp']['timeout'] ?: $_W['setting']['remote']['ftp']['overtime'],
						'rootdir' => $_W['setting']['remote']['ftp']['rootdir'] ?: $_W['setting']['remote']['ftp']['dir'],
					);
					$ftp = new Ftp($ftp_config);
					if (true === $ftp->connect()) {
						$response = $ftp->upload(ATTACHMENT_ROOT . '/' . $filename, $filename);
						if ($auto_delete_local) {
							file_delete($filename);
						}
						if (!empty($response)) {
							return true;
						} else {
							return error(1, '远程附件上传失败，请检查配置并重新上传');
						}
					} else {
						return error(1, '远程附件上传失败，请检查配置并重新上传');
					}  
		        }elseif(ATTACHMENT_TYPE == '2'){
					//阿里oss删除附件
					require_once(ROOT_D.'/core/library/alioss/autoload.php');
					$url=$this->setting['ali_endpoint'];
					$ossClient = make_oss_Client($this->setting['ali_accessid'], $this->setting['ali_accesskey'], $url);
					try {
						$ossClient->deleteObject($this->setting['ali_bucket'],$filename);
					} catch (OssException $e) {
						printf($e->getMessage() . "\n");
						return;
					}
				}elseif(ATTACHMENT_TYPE == '3'){
					//七牛删除附件
					require_once(ROOT_D . '/core/library/qiniu/autoload.php');
					$auth = qndel($this->setting['qiniu_accesskey'], $this->setting['qiniu_secretkey']);
					$config = new \Qiniu\Config();
					$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
					$err = $bucketManager->delete($this->setting['qiniu_bucket'], $filename);
					if ($err) {
						print_r($err);
					}
		        }elseif(ATTACHMENT_TYPE == '4'){
					//腾讯cos 删除附件
					require(ROOT_D.'/core/library/cos/sample.php');
					$config = array(
						'app_id' => $this->setting['tx_appid'],
						'secret_id' => $this->setting['tx_secretid'],
						'secret_key' => $this->setting['tx_secretkey'],
						'region' => $this->setting['region'],   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
						'timeout' => 60
					);
				
					$cosApi = make_cos_api($config);
					$ret = $cosApi->delFile($this->setting['tx_bucket'], $filename);
					if($ret['code']!=0){
						//exi('删除失败：'.$ret['message'],'error');
					}
		        }elseif(ATTACHMENT_TYPE == 5){
					$this->source_diy_request('del',array('file'=>$filename));
				}
		}
		if($isid){
			pdo_delete('core_attachment',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}else{
			pdo_delete('core_attachment',array('attachment'=>$id,'uniacid'=>$_SESSION['uniacid']));
		}		
		return true;
	}
	//图片缩略
	public function file_image_thumb($srcfile, $desfile = '', $width = 0) {
		global $_AR;
		if (!file_exists($srcfile)) {
			return error( '原图像不存在');
		}
		if (!$width){
			$width = $this->setting['width'];
		}
		$width=intval($width);
		if(!$width){
			$width=800;
		}
		if (empty($desfile)) {
			$ext = pathinfo($srcfile, PATHINFO_EXTENSION);
			$desfile=$this->get_source_name('image',$ext);
			$desfile=ROOT_AT.$desfile;
		}
		$org_info = @getimagesize($srcfile);
		if (!$org_info){
			exi( '获取原始图像信息失败','error');
		}
		if ($width == 0 || $width > $org_info[0]) {
			copy($srcfile, $desfile);
            $desfile=$this->file_image_water($desfile);
			return $desfile;
		}
		if(function_exists("ini_set")){
			ini_set("memory_limit", "600M");
		}
		if ($org_info[2] == 2) {
			if (function_exists("imagecreatefromjpeg")) {
				$img_org = imagecreatefromjpeg($srcfile);
			}
		}elseif ($org_info[2] == 3){
			if (function_exists("imagecreatefrompng")) {
				$img_org = imagecreatefrompng($srcfile);
				imagesavealpha($img_org, true);
			}
		}else{
			copy($srcfile, $desfile);
            $desfile=$this->file_image_water($desfile);
			return $desfile;
		}
		$scale_org = $org_info[0] / $org_info[1];
		$height = $width/$scale_org;
		if (function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$img_dst = imagecreatetruecolor($width, $height)) {
			imagealphablending($img_dst, false);
			imagesavealpha($img_dst, true);
			imagecopyresampled($img_dst, $img_org, 0, 0, 0, 0, $width, $height, $org_info[0], $org_info[1]);
		}else{
			exi( 'PHP环境不支持图片处理','error');
		}
		if ($org_info[2] == 2) {
			if (function_exists('imagejpeg')) {
				imagejpeg($img_dst, $desfile);
			}
		} else {
			if (function_exists('imagepng')) {
				imagepng($img_dst, $desfile);
			}
		}
		imagedestroy($img_dst);
		imagedestroy($img_org);
        $desfile=$this->file_image_water($desfile);
		return $desfile;
	}
	//图片裁剪
	public function file_image_crop($src, $desfile, $width = 400, $height = 300, $position = 1) {
		if (!file_exists($src)) {
			return error( '原图像不存在');
		}
		if (intval($width) <= 0 || intval($height) <= 0) {
			return error( '裁剪尺寸无效');
		}
		if (intval($position) > 9 || intval($position) < 1) {
			return error( '裁剪位置无效');
		}

		$des = dirname($desfile);
			if (!file_exists($des)) {
			if (!$this->mkdirs($des)) {
				return error( '创建目录失败');
			}
		} elseif (!is_writable($des)) {
			return error( '目录无法写入');
		}
			$org_info = @getimagesize($src);
		if ($org_info) {
			if ($org_info[2] == 1) { 			if (function_exists("imagecreatefromgif")) {
					$img_org = imagecreatefromgif($src);
				}
			} elseif ($org_info[2] == 2) {
				if (function_exists("imagecreatefromjpeg")) {
					$img_org = imagecreatefromjpeg($src);
				}
			} elseif ($org_info[2] == 3) {
				if (function_exists("imagecreatefrompng")) {
					$img_org = imagecreatefrompng($src);
				}
			}
		} else {
			return error( '获取原始图像信息失败');
		}

			if ($width == '0' || $width > $org_info[0]) {
			$width = $org_info[0];
		}
		if ($height == '0' || $height > $org_info[1]) {
			$height = $org_info[1];
		}
			switch ($position) {
			case 0 :
			case 1 :
				$dst_x = 0;
				$dst_y = 0;
				break;
			case 2 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = 0;
				break;
			case 3 :
				$dst_x = $org_info[0] - $width;
				$dst_y = 0;
				break;
			case 4 :
				$dst_x = 0;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 5 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 6 :
				$dst_x = $org_info[0] - $width;
				$dst_y = ($org_info[1] - $height) / 2;
				break;
			case 7 :
				$dst_x = 0;
				$dst_y = $org_info[1] - $height;
				break;
			case 8 :
				$dst_x = ($org_info[0] - $width) / 2;
				$dst_y = $org_info[1] - $height;
				break;
			case 9 :
				$dst_x = $org_info[0] - $width;
				$dst_y = $org_info[1] - $height;
				break;
			default:
				$dst_x = 0;
				$dst_y = 0;
		}
		if ($width == $org_info[0]) {
			$dst_x = 0;
		}
		if ($height == $org_info[1]) {
			$dst_y = 0;
		}

		if (function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$img_dst = imagecreatetruecolor($width, $height)) {
			imagecopyresampled($img_dst, $img_org, 0, 0, $dst_x, $dst_y, $width, $height, $width, $height);
		} else {
			return error( 'PHP环境不支持图片处理');
		}
		if (function_exists('imagejpeg')) {
			imagejpeg($img_dst, $desfile);
		} elseif (function_exists('imagepng')) {
			imagepng($img_dst, $desfile);
		}
		imagedestroy($img_dst);
		imagedestroy($img_org);
		return true;
	}
    //图片水印
    public function file_image_water($srcfile='') {
        if(!$this->setting['image_yin'] || !$this->setting['image_yinimg'] || !$srcfile){
            return $srcfile;
        }
        if (!file_exists($srcfile)) {
            return $srcfile;
        }
        $temp = pathinfo($srcfile);
        $name = $temp['basename'];
        $path = $temp['dirname'];
        $savefile = $path .'/'. $name;
        $image_yinimg=ROOT_AT.$this->setting['image_yinimg'];
        if (!file_exists($image_yinimg)) {
            return $srcfile;
        }
        $image_wei=$this->setting['image_wei']?:3;
        $image_yinrate=$this->setting['image_yinrate']?:30;
        $srcinfo = @getimagesize($srcfile);
        if (!$srcinfo) {
            return $srcfile;
        }
        $waterinfo = @getimagesize($image_yinimg);
        if (!$waterinfo) {
            return $srcfile;
        }
        switch ($image_wei) {
            //1顶部居左
            case 1: $x=$y=5; break;
            //2顶部居右
            case 2: $x = $srcinfo[0]-$waterinfo[0]; $y = 5; break;
            //3居中
            case 3: $x = ($srcinfo[0]-$waterinfo[0])/2; $y = ($srcinfo[1]-$waterinfo[1])/2; break;
            //4底部居左
            case 4: $x = 5; $y = $srcinfo[1]-$waterinfo[1]; break;
            //5底部居右
            case 5: $x = $srcinfo[0]-$waterinfo[0]; $y = $srcinfo[1]-$waterinfo[1]; break;
            default: $x=$y=5;
        }
        $srcImgObj = $this->image_create_from_ext($srcfile);
        if (!$srcImgObj) {
            return $srcfile;
        }
        $waterImgObj = $this->image_create_from_ext($image_yinimg);
        if (!$waterImgObj) {
            return $srcfile;
        }
        $this->imagecopymerge_gc($srcImgObj, $waterImgObj, $x, $y, 0, 0, $waterinfo[0], $waterinfo[1], $image_yinrate);
        switch ($srcinfo[2]) {
            case 1: imagegif($srcImgObj, $savefile); break;
            case 2: imagejpeg($srcImgObj, $savefile); break;
            case 3: imagepng($srcImgObj, $savefile); break;
            default: return $srcfile;
        }
        imagedestroy($srcImgObj);
        imagedestroy($waterImgObj);
        return $savefile;
    }
    /**
     * 由文件或 URL 创建一个新图象
     */
    public function image_create_from_ext($imgfile)
    {
        $info = getimagesize($imgfile);
        $im = null;
        switch ($info[2]) {
            case 1: $im=imagecreatefromgif($imgfile); break;
            case 2: $im=imagecreatefromjpeg($imgfile); break;
            case 3: $im=imagecreatefrompng($imgfile); break;
        }
        return $im;
    }
    /**
     * 将背景透明的陪你过图片与背景不透明的jpg图片合成一张
     * 并保持png图片背景透明
     */
    function imagecopymerge_gc($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
        // 透明度
        $opacity = $pct;
        // 获取水印图片宽
        $w = imagesx($src_im);
        // 获取水印图片高
        $h = imagesy($src_im);
        // 函数用于创建一幅空白图像
        $cut = imagecreatetruecolor($src_w, $src_h);
        //  拷贝图像的一部分
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        // 计算透明度
        // $opacity = 100 - $opacity;
        // 生成水印，将水印放到生成的空白图像上
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        // 再将要加水印的图片与其合成一张图片，为其设置透明度
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity);
    }
}